<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    body{
        height: 5000px;
    }
</style>
<body>
<script>
    // document.body.onscroll = function() {
    //     console.log(111)
    // }
    document.body.onscroll = throttle(scroll, 1000);

    function throttle(handle, wait = 300) {
        let initTime = new Date();
        let timer = null;
        return function proxy(...args) {
            const now = new Date();
            const self = this;
            const delta = wait - (now - initTime);
            // 小于等于0说明是低频操作，可以立即执行函数
            // 为啥要加else...if因为在这个时间差内有可能多次执行函数，这时候我们只用执行一次
            if (delta <= 0) {
                handle.apply(self, args);
                clearTimeout(timer);
                timer = null;
                initTime = new Date();
            } else if (!timer) {
                timer = setTimeout(() => {
                    clearTimeout(timer);
                    timer = null;
                    handle.apply(self, args);
                    initTime = new Date();
                }, delta);
            }
        }
    }

    function scroll() {
        console.log(111)
    }
</script>
</body>
</html>